import Taro, { Component } from '@tarojs/taro'
import {View, Text, Image, ScrollView} from '@tarojs/components'
import { ButtonItem, CheckboxItem, Loading, Empty, ItemFlow } from '@components'
import { AtInputNumber, AtSwipeAction } from 'taro-ui'
import { connect } from '@tarojs/redux'
import * as actions from '@actions/cart'
import { dispatchItemRecommend } from '@actions/item'
import { getWindowHeight } from '@utils/style'
import empty from "@assets/cart-empty.png"
import jump from "@utils/jump"
import Tip from './tip'
import './cart.scss'

@connect(state => state.cart, { ...actions, dispatchItemRecommend } )
class Cart extends Component {
  config = {
    navigationBarTitleText: '购物车',
    enablePullDownRefresh: true,
    backgroundTextStyle: 'dark'
  }

  constructor (props) {
    super(props)
    this.state = {
      loading: true,
      login: false,
      recommendList: [],
      opended: -1
    }
  }

  componentDidShow() {
    if(Taro.getStorageSync('token')) {
      this.loadCartInfo()
    } else {
      this.setState({ loading: false, login: false })
    }
    this.props.dispatchItemRecommend().then(data => {
      this.setState({recommendList: data.itemList})
    })
  }

  onPullDownRefresh() {
    this.loadCartInfo()
    Taro.stopPullDownRefresh()
  }

  loadCartInfo = () => {
    this.props.dispatchCart().then(() => {
      this.setState({
        loading: false,
        login: true
      })
    }).catch(() => {
      this.setState({ loading: false, login: false })
    })
  }

  toLogin = () => {
    jump({
      url: '/pages/userLogin/userLogin'
    })
  }

  toHome = () => {
    jump({
      method: 'switchTab',
      url: '/pages/home/home'
    })
  }

  handleItemCheck = (item, index) => {
    Taro.showLoading()
    this.props.dispatchCartUpdate({
      skuId: item.skuId,
      itemNum: item.num,
      checked: !item.checked
    }).then(() => {
      this.loadCartInfo()
      Taro.hideLoading()
    })
  }

  handleUpdateNum = (item, index, num) => {
    Taro.showLoading()
    this.props.dispatchCartUpdate({
      skuId: item.skuId,
      itemNum: num,
      checked: true
    }).then(() => {
      this.loadCartInfo()
      Taro.hideLoading()
    })
  }

  handleAllCheck = () => {
    const { cartInfo } = this.props
    Taro.showLoading()
    this.props.dispatchCartSelectAll({
      checked : !cartInfo.allChecked
    }).then(() => {
      this.loadCartInfo()
      Taro.hideLoading()
    }).catch(() => Taro.hideLoading())
  }

  handleOrder = () => {
    const { cartInfo } = this.props
    if (cartInfo.itemNum === 0) {
      Taro.showToast({
        title: '请选择商品',
        icon: 'none'
      })
      return
    }

    const { cartGroupList = [] } = cartInfo
    let items = []
    cartGroupList.map(group => {
      group.itemList.filter(item => item.checked).map(item => {
        items.push({
          skuId: item.skuId, itemId: item.itemId, itemNum: item.itemNum
        })
      })
    })
    jump({
      url: '/pages/orderSettlement/orderSettlement',
      payload: {
        fromType: 0,
        items: encodeURIComponent(JSON.stringify(items))
      }
    })
  }

  handleItemDelete = (skuId) => {
    Taro.showLoading()
    this.props.dispatchCartDelete({skuIds: skuId}).then(() => {
      this.setState({opended: -1})
      this.loadCartInfo()
      Taro.hideLoading()
    }).catch(() => Taro.hideLoading())
  }

  handleSingle(skuId) {
    this.setState({opended: skuId})
  }

  render () {
    const { cartInfo } = this.props
    const { cartGroupList = [], allChecked, totalPrice, itemNum, policyDescList } = cartInfo
    const disabled = (itemNum === 0)
    const { recommendList } = this.state

    if (this.state.loading) {
      return <Loading />
    }
    const BUTTON = {
      width: Taro.pxTransform(200),
      height: Taro.pxTransform(65),
      borderRadius: Taro.pxTransform(30),
      marginTop: Taro.pxTransform(20),
      marginBottom: Taro.pxTransform(20),
      marginRight: Taro.pxTransform(20)
    }

    if (!this.state.login) {
      return (
        <View className='cart' style={{ height: getWindowHeight() }}>
          <Tip list={policyDescList} />
          <Empty image={empty} text='未登录' btn='登录' onClick={this.toLogin.bind(this)} />

          {/* 猜你喜欢 */}
          {
            recommendList &&
            <View>
              <View className='user__recommend'>
                <Text className='user__recommend-txt'>猜你喜欢</Text>
              </View>
              <ItemFlow list={recommendList} showTitle='true' />
            </View>
          }
        </View>
      )
    }

    if (!cartGroupList || cartGroupList.length == 0) {
      return (
        <View className='cart' style={{ height: getWindowHeight() }}>
          <Tip list={policyDescList} />
          <Empty image={empty} text='购物车空空如也' btn='去逛逛' onClick={this.toHome.bind(this)} />

          {/* 猜你喜欢 */}
          {
            recommendList &&
            <View>
              <View className='user__recommend'>
                <Text className='user__recommend-txt'>猜你喜欢</Text>
              </View>
              <ItemFlow list={recommendList} showTitle='true' />
            </View>
          }
        </View>
      )
    }

    return (
      <View className='cart'>
        <ScrollView
          scrollY
          className='cart__wrap'
          style={{ height: getWindowHeight() }}
        >
          <Tip list={policyDescList} />

          {cartGroupList.map((group, gindex) => (
            <View className='cart-list' key={`${group.promId}_${gindex}`}>
              {group.itemList.map((item, index) => (
                <AtSwipeAction
                  key={item.skuId}
                  onOpened={this.handleSingle.bind(this, item.skuId)}
                  onClick={this.handleItemDelete.bind(this, item.skuId)}
                  isOpened={item.skuId === this.state.opended}
                  options={[{text: '删除', style: {backgroundColor: '#E32D2F'}}]}
                >
                <View key={item.id} className='cart-list__item'>
                  <CheckboxItem checked={item.checked} onClick={this.handleItemCheck.bind(this, item, index)} />
                  <Image className='cart-list__item-img' src={item.itemImage} />

                  <View className='cart-list__item-info'>
                    <View className='cart-list__item-title'>
                      {!!item.prefix &&
                      <Text className='cart-list__item-title-tag'>{item.prefix}</Text>
                      }
                      <Text className='cart-list__item-title-name' numberOfLines={1}>
                        {item.itemName}
                      </Text>
                    </View>

                    <View className='cart-list__item-spec'>
                      <Text className='cart-list__item-spec-txt'>
                        {item.itemSpec}
                      </Text>
                    </View>

                    <View className='cart-list__item-wrap'>
                      <Text className='cart-list__item-price'>
                        ¥{item.sellingPrice}
                      </Text>
                      <View className='cart-list__item-num'>
                        <AtInputNumber
                          step={1}
                          min={1}
                          value={item.itemNum}
                          onChange={this.handleUpdateNum.bind(this, item, index)}
                        />
                      </View>
                    </View>

                  </View>
                </View>
                </AtSwipeAction>
              ))}
            </View>
          ))}

          {/* 猜你喜欢 */}
          {
            recommendList &&
            <View>
              <View className='user__recommend'>
                <Text className='user__recommend-txt'>猜你喜欢</Text>
              </View>
              <ItemFlow list={recommendList} showTitle='true' />
            </View>
          }


        </ScrollView>

        <View className='cart__footer'>
          <View className='cart-footer'>
            <View className='cart-footer__select'>
              <CheckboxItem
                checked={allChecked}
                onClick={this.handleAllCheck}
              >
                <Text className='cart-footer__select-txt'>全选</Text>
              </CheckboxItem>
            </View>
            <View className='cart-footer__amount'>
              <Text className='cart-footer__amount-txt'>
                ¥{totalPrice}
              </Text>
            </View>
            {disabled ?
              <View className='cart-footer__btn'>
                <ButtonItem text='下单' compStyle={BUTTON} disabled />
              </View>
              :
              <View className='cart-footer__btn'>
                <ButtonItem type='primary' text='下单' compStyle={BUTTON} onClick={this.handleOrder} />
              </View>
            }
          </View>
        </View>

      </View>
    )
  }
}

export default Cart
